package sshftp

import (
	"fmt"
	"io"
	"os"
	"strings"
)

/*
ftp相关操作
 */

//远程创建文件或目录
func (this *Client) FtpCreate(filePath string) (io.ReadWriteCloser,error)  {
	err := this.connect()
	if err!=nil{
		return nil, err
	}
	create, err := this.sftpClient.Create(filePath)
	return create,err
}

//删除远程文件
func (this *Client) FtpRemove(filePath string) (err error)  {
	err = this.connect()
	if err!=nil{
		return  err
	}
	err = this.sftpClient.Remove(filePath)
	return err
}

//上传文件内容到远程写入文件
func (this *Client) FtpUploadWithContent(content string,destPath string) (err error)  {
	reader := strings.NewReader(content)
	dester, err := this.FtpCreate(destPath)
	if err!=nil{
		return err
	}
	defer dester.Close()
	return this.upload(reader,dester,1000000)

}

//上传文件到远程
func (this *Client) FtpUpload(srcPath string,destPath string) (err error)  {

	//reader := strings.NewReader(content)
	reader, err := os.Open(srcPath)
	if err!=nil{
		return err
	}
	defer reader.Close()
	dester, err := this.FtpCreate(destPath)
	if err!=nil{
		return err
	}
	defer dester.Close()
	return this.upload(reader,dester,1000000)
}


//上传文件
func (this *Client) upload(source io.Reader, destination io.Writer, size int) error {
	if err := this.connect(); err != nil {
		return fmt.Errorf("connect: %w", err)
	}

	chunk := make([]byte, size)

	for {
		num, err := source.Read(chunk)
		if err == io.EOF {
			tot, err := destination.Write(chunk[:num])
			if err != nil {
				return err
			}

			if tot != len(chunk[:num]) {
				return fmt.Errorf("failed to write stream")
			}

			return nil
		}

		if err != nil {
			return err
		}

		tot, err := destination.Write(chunk[:num])
		if err != nil {
			return err
		}

		if tot != len(chunk[:num]) {
			return fmt.Errorf("failed to write stream")
		}
	}
}

// Download returns remote/destination file for reading.
func (this *Client) Download(filePath string) (io.ReadCloser, error) {
	if err := this.connect(); err != nil {
		return nil, fmt.Errorf("connect: %w", err)
	}

	return this.sftpClient.Open(filePath)
}

// Info gets the details of a file. If the file was not found, an error is returned.
func (this *Client) Info(filePath string) (os.FileInfo, error) {
	if err := this.connect(); err != nil {
		return nil, fmt.Errorf("connect: %w", err)
	}
	info, err := this.sftpClient.Lstat(filePath)
	if err != nil {
		return nil, fmt.Errorf("file stats: %w", err)
	}
	return info, nil
}





